package cn.xclink.kernel.web;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import cn.xclink.common.web.BaseController;
import cn.xclink.common.web.bind.annotation.CurrentUser;
import cn.xclink.kernel.entity.Resource;
import cn.xclink.kernel.entity.User;
import cn.xclink.kernel.service.ResourceService;
import cn.xclink.kernel.service.UserService;
import cn.xclink.kernel.util.ValidateCodeUtils;

@Controller
public class LoginController extends BaseController<User> {

	@Autowired
	private ResourceService resourceService;
	@Autowired
	private UserService userService;

	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String login(Model model) {
		// 判断用户是否登录
		if (SecurityUtils.getSubject().isAuthenticated()) {
			return "redirect:/";
		}
		// 默认赋值message,避免freemarker尝试从session取值,造成异常
		model.addAttribute("message", "");
		return "login";
	}

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String login(Model model, HttpServletRequest request)
			throws Exception {
		//在这里进行验证码的校验
		//从session获取正确验证码
		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
		HttpSession session =httpServletRequest.getSession();
		//取出session的验证码（正确的验证码）
		String validateCode = (String) session.getAttribute("validateCode");
		
		//取出页面的验证码
		//输入的验证和session中的验证进行对比 
		String validateCodeFromPage = httpServletRequest.getParameter("validateCode");
		if(validateCodeFromPage!=null && validateCode!=null && !validateCodeFromPage.equals(validateCode)){
			model.addAttribute("message", "验证码错误");
			return "login";
		}
	
		String j_account = request.getParameter("j_account");
		String j_password = request.getParameter("j_password");

		Subject user = SecurityUtils.getSubject();
		// 通过账号和密码获取 UsernamePasswordToken token
		UsernamePasswordToken token = new UsernamePasswordToken(j_account, j_password);
		if (StringUtils.isNotBlank(request.getParameter("rememberMe"))) {
			token.setRememberMe(true);
		} else {
			token.setRememberMe(false);
		}
		try {
			// 会调用 shiroDbRealm 的认证方法
			// doGetAuthenticationInfo(AuthenticationToken)
			user.login(token);
		} catch (UnknownAccountException uae) {
			model.addAttribute("message", "账号或密码错误!");
			return "login";
		} catch (IncorrectCredentialsException ice) {
			model.addAttribute("message", "账号或密码错误!");
			return "login";
		} catch (LockedAccountException lae) {
			model.addAttribute("message", "账号被锁定!");
			return "login";
		} catch (Exception e) {
			model.addAttribute("message", "未知错误,请联系管理员.");
			return "login";
		}
		return "redirect:/";
	}

	@RequestMapping("/")
	public String index(@CurrentUser User loginUser, Model model) {
		Map<String,List<Resource>> treeMap = resourceService.findUserResourceByUserId(loginUser.getUserId());
		model.addAttribute("treeMap", treeMap);
		return "index";
	}

	@RequestMapping("/welcome")
	public String welcome() {
		return "welcome";
	}
	
	@RequestMapping("/validateCode")
	public void validateCode(HttpServletRequest request, HttpServletResponse response) throws IOException{
        response.setHeader("Pragma", "No-cache");  
        response.setHeader("Cache-Control", "no-cache");  
        response.setDateHeader("Expires", 0);  
        response.setContentType("image/jpeg");  
          
        //生成随机字串  
        String verifyCode = ValidateCodeUtils.generateVerifyCode(4);  
        //存入会话session  
        HttpSession session = request.getSession(true);  
        session.setAttribute("validateCode", verifyCode.toLowerCase());  
        //生成图片  
        int w = 200, h = 80;  
        ValidateCodeUtils.outputImage(w, h, response.getOutputStream(), verifyCode);  
	}
}
